// ================================我是立即购买结算页面===========================================

import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import styles from "../style/buynow.module.css";
import leftImg from "../img/left.png";
import { address } from "../api/address"; //收货地址接口
import { pay } from "../api/order"; //支付接口
interface PurchaseData {
  id: string;
  name: string;
  price: string;
  originalPrice: string;
  image: string;
  selectedSpec: string;
  quantity: number;
  deliveryAddress: string;
  selectedTime: string;
}

interface Address {
  id: number;
  name: string;
  tel: string;
  default: number; // 1表示默认地址
  address: string;
}

interface NormItem {
  name: string;
  value: string;
}

// 立即购买页面组件
const BuynowPage = () => {
  const navigate = useNavigate(); // 获取路由导航函数
  const [quantity, setQuantity] = useState(1); // 商品数量状态，初始为1
  const [showHint, setShowHint] = useState(false); // 控制提示框显示
  const [productData, setProductData] = useState<PurchaseData | null>(null); // 商品数据
  const [shopID, setShopID] = useState(""); // 店铺ID
  const [addressList, setAddressList] = useState<Address[]>([]); // 地址列表
  const [addID, setAddID] = useState<number | null>(null); // 选中的地址ID
  const [normData, setNormData] = useState<NormItem[]>([]); // 规格数据
  const [isSubmitting, setIsSubmitting] = useState(false); // 提交状态

  // 安全获取本地存储的用户数据
  const getUserData = () => {
    try {
      const user = localStorage.getItem("user");
      return user ? JSON.parse(user) : null;
    } catch (error) {
      console.error("解析用户数据失败:", error);
      return null;
    }
  };

  const user = getUserData(); // 获取用户数据

  // 组件挂载时从本地存储读取商品数据
  useEffect(() => {
    const storedData = localStorage.getItem("currentPurchase");
    console.log(storedData, "本地存储中的商品数据");

    if (storedData) {
      try {
        const data: PurchaseData = JSON.parse(storedData);
        const norm: NormItem[] = [
          {
            name: data.name,
            value: data.selectedSpec,
          },
        ];

        setNormData(norm);
        setShopID(data.id); // 设置店铺ID
        setProductData(data);
        setQuantity(data.quantity); // 设置商品数量
      } catch (error) {
        console.error("解析商品数据失败:", error);
        navigate("/"); // 解析失败则返回首页
      }
    } else {
      navigate("/"); // 没有商品数据则返回首页
    }
  }, [navigate]);

  // 用户数据变化时获取地址信息
  useEffect(() => {
    const fetchAddress = async () => {
      if (!user?.data?.id) return; // 没有用户ID则不获取

      try {
        const response = await address({ uid: user.data.id }); // 调用地址API

        if (response.data?.data?.length > 0) {
          setAddressList(response.data.data);
          // 查找默认地址，没有则使用第一个地址
          const defaultAddress = response.data.data.find(
            (addr: Address) => addr.default === 1
          );
          setAddID(defaultAddress?.id || response.data.data[0].id);
        }
      } catch (error) {
        console.error("获取地址失败:", error);
      }
    };

    fetchAddress();
  }, [user]);

  // 处理商品数量变化
  const handleQuantity = (type: "add" | "subtract") => {
    setQuantity((prev) => {
      const newQuantity = Math.max(1, type === "add" ? prev + 1 : prev - 1);

      if (productData) {
        // 更新本地存储的商品数量
        const updatedData = { ...productData, quantity: newQuantity };
        localStorage.setItem("currentPurchase", JSON.stringify(updatedData));
      }

      return newQuantity;
    });
  };

  // 处理输入框数量变化
  const handleQuantityChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newQuantity = Math.max(1, +e.target.value);
    setQuantity(newQuantity);

    if (productData) {
      // 更新本地存储的商品数量
      const updatedData = { ...productData, quantity: newQuantity };
      localStorage.setItem("currentPurchase", JSON.stringify(updatedData));
    }
  };

  // 立即购买处理函数
  const handleBuy = async () => {
    // 验证必要信息
    if (!productData || quantity < 1 || !addID) {
      setShowHint(true); // 显示提示
      setTimeout(() => setShowHint(false), 2000); // 2秒后隐藏
      return;
    }

    setIsSubmitting(true); // 设置提交状态

    try {
      console.log("提交的数据:", {
        user_id: user.data.id,
        address_id: addID,
        goods_id: shopID,
        num: quantity,
        norm: productData.selectedSpec,
        money: (parseFloat(productData.price) * quantity).toFixed(2),
      });

      // 调用支付API
      const response = await pay({
        user_id: user.data.id,
        address_id: addID,
        goods_id: shopID,
        num: quantity,
        norm: productData.selectedSpec,
        money: (parseFloat(productData.price) * quantity).toFixed(2),
      });

      if (response.data.code === 1) {
        navigate("/successful"); // 支付成功跳转
      } else {
        console.error("订单支付失败:", response.data.message);
        console.log(response.data);
        setShowHint(true); // 显示失败提示
        setTimeout(() => setShowHint(false), 2000);
      }
    } catch (error) {
      console.error("API error:", error);
      setShowHint(true); // 显示错误提示
      setTimeout(() => setShowHint(false), 2000);
    } finally {
      setIsSubmitting(false); // 重置提交状态
    }
  };

  if (!productData) {
    return <div className={styles.loading}>加载中...</div>;
  }

  const goBack = () => navigate(-1); //返回上一页
  return (
    <div className={styles.container}>
      {/* 顶部导航 */}
      <div className={styles.top}>
        <div>
          <img onClick={goBack} src={leftImg} alt="" />
          <b>订单购买</b>
        </div>
      </div>

      {/* 地址选择 */}
      <div
        className={styles.addressSection}
        onClick={() => navigate("/address")}
      >
        <div className={styles.addressContent}>
          <span className={styles.addressHint}>
            <span className={styles.addressText}>
              {addressList.length > 0
                ? (() => {
                    // 优化查找逻辑并添加类型注解
                    const selectedAddress = addressList.find(
                      (addr: Address) => addr.id === addID
                    );
                    return selectedAddress
                      ? `${selectedAddress.name} ${selectedAddress.address}`
                      : "请选择收货地址";
                  })()
                : "请选择收货地址"}
            </span>
          </span>
        </div>
        <img
          src={require("../img/right.png")}
          alt="箭头"
          className={styles.arrowIcon}
        />
      </div>

      {/* 商品信息 */}
      <div className={styles.productCard}>
        <img src={productData.image} alt="商品图片" />
        <div className={styles.productInfo}>
          <h3>{productData.name}</h3>
          <p>{productData.selectedSpec}</p>
          <div className={styles.priceRow}>
            <span className={styles.price}>
              ￥{parseFloat(productData.price).toFixed(2)}
            </span>
            <div className={styles.quantityControl}>
              <button
                className={styles.quantityControlButton}
                onClick={() => handleQuantity("subtract")}
                aria-label="减少数量"
              >
                <img src={require("../img/jian.png")} alt="减少" />
              </button>
              <input
                type="number"
                value={quantity}
                onChange={(e) => {
                  const newQuantity = Math.max(1, +e.target.value);
                  setQuantity(newQuantity);
                  // 更新本地存储
                  const updatedData = { ...productData, quantity: newQuantity };
                  localStorage.setItem(
                    "currentPurchase",
                    JSON.stringify(updatedData)
                  );
                }}
                aria-label="购买数量"
                min="1"
              />
              <button
                className={styles.quantityControlButton}
                onClick={() => handleQuantity("add")}
                aria-label="增加数量"
              >
                <img src={require("../img/add.png")} alt="增加" />
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 价格明细 */}
      <div className={styles.priceDetails}>
        <div className={styles.priceRow}>
          <span>商品金额:</span>
          <span>￥{productData.price}</span>
        </div>
        <div className={styles.priceRow}>
          <span>运费:</span>
          <span>￥0</span>
        </div>
        <div className={styles.priceRow}>
          <span>优惠抵扣:</span>
          <span>
            ￥
            {(
              parseFloat(productData.originalPrice) -
              parseFloat(productData.price)
            ).toFixed(2)}
          </span>
        </div>
        <div className={styles.divider} />
        <div className={styles.totalPrice}>
          <span>总价:</span>
          <span className={styles.amount}>
            ￥{(parseFloat(productData.price) * quantity).toFixed(2)}
          </span>
        </div>
      </div>

      {/* 底部操作栏 */}
      <div className={styles.footer}>
        <div className={styles.total}>
          总价:{" "}
          <span>￥{(parseFloat(productData.price) * quantity).toFixed(2)}</span>
        </div>
        <button
          className={styles.buyButton}
          onClick={handleBuy}
          disabled={isSubmitting}
        >
          {isSubmitting ? "提交中..." : "立即购买"}
        </button>
      </div>
    </div>
  );
};

export default BuynowPage;
